import fs from "fs";
import { Province } from "../../models/Province.mjs";
import { transformProvinceData } from "../../utils/dataTransform.mjs";

export class ImportService {
  static async importProvinceData(file) {
    if (!file || !file.path) {
      throw new Error("未接收到文件");
    }

    try {
      // 从文件路径读取内容
      const content = fs.readFileSync(file.path, "utf8");
      const provinceData = JSON.parse(content);

      if (typeof provinceData !== "object") {
        throw new Error("数据格式不正确，应为对象格式");
      }

      // 清空现有数据
      await Province.deleteMany({});

      // 转换并导入数据
      const provinces = Object.entries(provinceData).map((data) =>
        transformProvinceData(data)
      );

      if (provinces.length > 0) {
        await Province.insertMany(provinces);

        // 删除临时文件
        fs.unlinkSync(file.path);

        return {
          message: "省份数据导入成功",
          count: provinces.length,
        };
      } else {
        throw new Error("没有有效的省份数据可以导入");
      }
    } catch (error) {
      // 确保清理临时文件
      if (file && file.path) {
        try {
          fs.unlinkSync(file.path);
        } catch (unlinkError) {
          console.error("清理临时文件失败:", unlinkError);
        }
      }
      throw error;
    }
  }
}
